package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.auth.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.model.AreaInfo;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.LImageLoader;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.truck.http.UserTruckRequest;
import com.shundr.truck.model.TruckInfo;

/**
 * 添加车辆 AddTruckActivity
 * 
 * @author larry 2015-4-27 下午2:30:31
 * @version 1.0.0
 *
 */
public class TruckDetailActivity extends BaseActivity implements
		OnClickListener {

	private Button btnPCode;// 省份代号
	private EditText etTruckNum;// 车牌号码
	private Button btnTruckType;// 车辆类型
	private EditText etTruckLoad;// 载重
	private EditText etTruckLength;// 长度

	private Button btnDirect;// 流向

	private Button btnSave;// 保存

	private String pType;// 车辆类型

	private ImageView ivFull;// 车辆照片
	private ImageView ivDriverCard;// 行驶证

	private PictureInfo mPTruckInfo;// 车辆照片
	private PictureInfo mPLisInfo;// 行驶证

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();
	private int flag = 0;
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private List<AreaInfo> mAreas = new ArrayList<AreaInfo>();

	private ImageLoader mImageLoader;

	private int mId;

	private TruckInfo mInfo;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserTruckRequest.ADD_TRUCK_SUCCESSED:
					ToastHelper.toastShort(mContext, msg.obj.toString());
					ProgressDialogHelper.dismiss();
					break;
				case UserTruckRequest.GET_TRUCK_INFO_SUCCESSED:
					mInfo = (TruckInfo) msg.obj;
					initData(mInfo);
					ProgressDialogHelper.dismiss();
					break;
				case UserTruckRequest.DELETE_TRUCK_SUCCESSED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					new Timer().schedule(new TimerTask() {

						@Override
						public void run() {
							setResult(888);
							finish();
						}
					}, 600);
					break;
				case UserTruckRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_truck_details);
		btnPCode = (Button) findViewById(R.id.btn_province_code);
		btnPCode.setVisibility(View.GONE);
		etTruckNum = (EditText) findViewById(R.id.et_truck_num);
		btnTruckType = (Button) findViewById(R.id.btn_truck_type);
		etTruckLoad = (EditText) findViewById(R.id.et_truck_load);
		etTruckLength = (EditText) findViewById(R.id.et_truck_leng);
		btnDirect = (Button) findViewById(R.id.btn_truck_direction);
		btnSave = (Button) findViewById(R.id.btn_save);

		btnSave.setVisibility(View.GONE);

		etTruckNum.setEnabled(false);
		etTruckLoad.setEnabled(false);
		etTruckLength.setEnabled(false);

		ivFull = (ImageView) findViewById(R.id.iv_car_full);
		ivDriverCard = (ImageView) findViewById(R.id.iv_driver);

		ivFull.setOnClickListener(this);
		ivDriverCard.setOnClickListener(this);

		this.mImageLoader = ImageLoader.getInstance();

		try {
			mId = getIntent().getIntExtra("id", -1);
			if (mId < 0) {
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		ProgressDialogHelper.show(mContext, "正在加载中...");
		new UserTruckRequest(mContext, mHandler).getTruckInfo(mId);
	}

	private void initData(TruckInfo info) {
		if (info == null) {
			return;
		}
		try {
			etTruckNum.setText(info.getTruckPlateNumber());
			mImageLoader.displayImage(info.getTruckPic(), ivFull,
					LImageLoader.mOptions);
			mImageLoader.displayImage(info.getTruckLicensePic(), ivDriverCard,
					LImageLoader.mOptions);
			btnTruckType.setText(info.getTruckType());
			etTruckLoad.setText(info.getTruckCapacity() + "");
			etTruckLength.setText(info.getTruckLength() + "");
			String direct = "";
			if (!StringUtil.isNull(info.getTruckForwardCity1())) {
				direct = direct + info.getTruckForwardCity1() + ",";
			}
			if (!StringUtil.isNull(info.getTruckForwardCity2())) {
				direct = direct + info.getTruckForwardCity2() + ",";
			}
			if (!StringUtil.isNull(info.getTruckForwardCity3())) {
				direct = direct + info.getTruckForwardCity3() + ",";
			}
			if (!StringUtil.isNull(info.getTruckForwardCity4())) {
				direct = direct + info.getTruckForwardCity4() + ",";
			}
			if (!StringUtil.isNull(direct)) {
				direct = direct.substring(0, direct.length() - 1);
			}
			btnDirect.setText(direct);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_car_full:
			Intent full = new Intent(mContext, PreviewActivity.class);
			full.putExtra("url", mInfo.getTruckPic());
			startActivity(full);
			break;
		case R.id.iv_driver:
			Intent driver = new Intent(mContext, PreviewActivity.class);
			driver.putExtra("url", mInfo.getTruckLicensePic());
			startActivity(driver);
			break;
		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			Uri data2 = null;
			if (data == null) {
				data2 = PictureUtil.getImageUri();
			} else {
				data2 = data.getData();
			}
			switch (requestCode) {
			case PictureUtil.PHOTO_PICKED_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				// 设置裁剪尺寸
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1.5);
				intent.putExtra("outputX", 250);
				intent.putExtra("outputY", 375);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.CAMERA_WITH_DATA:
				data2 = PictureUtil.getCameraImageCaiUri();
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1.5);
				intent.putExtra("outputX", 250);
				intent.putExtra("outputY", 375);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.PHOTO_CROP:
				Bundle bundle = data.getExtras();
				Bitmap myBitmap = (Bitmap) bundle.get("data");
				File file = Base64Util.saveBitmapToFile(myBitmap);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(myBitmap));
				myBitmap.recycle();
				info.setFilename(PictureUtil.getCharacterAndNumber() + ".png");
				if (flag == 0) {
					info.setType(PictureInfo.FileType.truck);
					mPTruckInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), ivFull,
							LImageLoader.mOptions);
				} else if (flag == 1) {
					info.setType(PictureInfo.FileType.truck_license);
					mPLisInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), ivDriverCard,
							LImageLoader.mOptions);
				}
				break;
			default:
				break;
			}
		} else if (requestCode == 502) {
			if (data != null) {
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json,
							AreaInfo.class);
					mAreas.clear();
					mAreas.addAll(areas);
					if (areas.size() > 0) {
						String selected = "";
						for (AreaInfo info : areas) {
							selected = selected + info.getName() + ",";
						}
						btnDirect.setText(selected.substring(0,
								selected.length() - 1));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1.5);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 400);
			intent.putExtra("outputY", 600);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESOULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		// menu.getItem(0).setTitle("删除");

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// switch (item.getItemId()) {
		// case R.id.menu_confirm:
		// DialogUtil.noticeAlertDialog(mContext, "删除", "是否确定删除此车辆？",
		// new OnDisplayListener() {
		//
		// @Override
		// public void confirm() {
		// ProgressDialogHelper.show(mContext, "正在删除中...");
		// new UserTruckRequest(mContext, mHandler).deleteTruck(mId);
		// }
		//
		// @Override
		// public void cancel() {
		//
		// }
		// });
		// break;
		//
		// default:
		// break;
		// }
		return super.onOptionsItemSelected(item);
	}

}
